/* 
 * File:   NetworkManager.cpp
 * Author: noe
 * 
 * Created on 7 octobre 2013, 19:11
 */

#include "NetworkManager.h";
#include "Game.h"

NetworkManager::NetworkManager() {
}

NetworkManager::NetworkManager(const NetworkManager& orig) {
}

NetworkManager::~NetworkManager() {
}

bool NetworkManager::connectTo(std::string adress)
{
	sock = socket(AF_INET, SOCK_STREAM, 0);
  
	sin.sin_addr.s_addr = inet_addr(adress.c_str());
	sin.sin_family = AF_INET;
	sin.sin_port = htons(PORT);
	
	if(connect(sock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR)
    {
		std::thread t1(&NetworkManager::readLoop, this);
		t1.detach();
		
//		thread = SDL_CreateThread(&NetworkManager::readLoop, NetworkManager);
		
		return true;
	}
	else
	{
		return false;
	}
	
	

}

bool NetworkManager::sendMessage(std::string msg)
{
	send(sock, msg.c_str(), msg.length(), 0);
}

void* NetworkManager::readLoop()
{
	this->messages.push_back("");
	while(true)
	{
		if(recv(sock, buffer, 32, 0))
		{
			this->messages.push_back(buffer);
//			std::cout << this->messages[this->messages.size() - 1] << "\n";
		}
	}
	return 0;
}

std::vector<std::string> NetworkManager::getMessages()
{
	this->msgcpy = this->messages;
	this->messages.clear();
	
	return this->msgcpy;

}




